package edu.uclm.esi.tysw.podtube.domain;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.SQLException;

import edu.uclm.esi.tysw.podtube.persistence.AudioDAO;

public class Audio {
	private String hash;
	private byte[] contenido;
	private String tempFileName;
	private String trueFileName;
	private String palabraClave1;
	private String palabraClave2;
	private String palabraClave3;
	private Usuario user;

	public Audio(String tempFileName, String trueFileName, String pC1, String pC2, String pC3) throws FileNotFoundException, IOException,
			NoSuchAlgorithmException {
		FileInputStream fi = new FileInputStream(tempFileName);
		this.contenido = new byte[fi.available()];
		fi.read(this.contenido);
		fi.close();

		this.tempFileName = tempFileName;
		this.trueFileName = trueFileName;
		this.palabraClave1 = pC1;
		this.palabraClave2 = pC2;
		this.palabraClave3 = pC3;
		this.hash = calculateMD5(tempFileName);
	}

	public void insert() throws SQLException, FileNotFoundException {
		AudioDAO.insert(this);
	}

	/*private String calculateHash() {
		String hash = "";
		for (byte aux : this.contenido) {
			int b = aux & 0xff;
			if (Integer.toHexString(b).length() == 1)
				hash += "0";
			hash += Integer.toHexString(b);
		}
		return hash;
	}*/

	private String calculateMD5(String tempFileName) throws NoSuchAlgorithmException, IOException {
		MessageDigest md = MessageDigest.getInstance("MD5");
		md.reset();
		FileInputStream fis = new FileInputStream(tempFileName);
		byte[] byte_array = new byte[fis.available()];

		int numBytes = 0;
		while ((numBytes = fis.read(byte_array)) != -1) {
			md.update(byte_array, 0, numBytes);
		}
		byte[] digest = md.digest();
		fis.close();

		StringBuilder sb = new StringBuilder();
		for (byte b : digest) {
			sb.append(String.format("%02x", b & 0xff));
		}

		return sb.toString();
	}

	public byte[] getContenido() {
		return contenido;
	}

	public String getHash() {
		return hash;
	}

	public String getTempFileName() {
		return tempFileName;
	}

	public String getTrueFileName() {
		return trueFileName;
	}

	public String getPalabraClave1() {
		return palabraClave1;
	}

	public String getPalabraClave2() {
		return palabraClave2;
	}

	public String getPalabraClave3() {
		return palabraClave3;
	}

	public void setUsuario(Usuario user) {
		this.user = user;
	}

	public Usuario getUsuario() {
		return user;
	}
}
